<template>
  <el-dialog
    :title="dialogTitle"
    :visible="visible"
    width="50%"
    @close="onDialogClose"
  >
    <!-- 绑定的form表单数据 -->
    <el-form ref="rolesForm" :rules="rolesFormRules" :model="rolesForm" label-width="80px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model.trim="rolesForm.roleName" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model.trim="rolesForm.roleDesc" placeholder="请输入角色描述" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onDialogClose">取 消</el-button>
      <el-button type="primary" @click="onSave">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addRole, getRoleDataById, editRole } from '@/api/role'
export default {
  model: {
    prop: 'visible'
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      // 添加的表单数据
      rolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 表单的校验规则
      rolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.rolesForm.roleId ? '修改角色' : '添加角色'
    }
  },
  created() {

  },

  methods: {
    // 对话框关闭，表单重置
    onDialogClose() {
      this.$emit('input', false)
      this.$refs.rolesForm.resetFields()
      this.rolesForm = {
        roleName: '',
        roleDesc: ''
      }
    },
    // 点击确定
    async onSave() {
      await this.$refs.rolesForm.validate()
      try {
        // 判断处于添加还是编辑状态
        if (this.rolesForm.roleId) {
        // 编辑
        // 发送请求修改用户
          await editRole(this.rolesForm.roleId, this.rolesForm)
          this.$message.success('修改成功！')
          this.$emit('edit-success')
        } else {
        // 添加
        // 发送请求添加用户
          await addRole(this.rolesForm)
          this.$message.success('添加成功！')
          this.$emit('add-success')
        }
        this.onDialogClose()
      } catch (err) {
        console.log(err)
      }
    },
    // 根据 ID 查询角色信息
    async getRoleDataById(id) {
      const res = await getRoleDataById(id)
      this.rolesForm = res
    }
  }
}
</script>

<style scoped lang='scss'>

</style>
